import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Response as ExpressResponse } from 'express';

export interface Response<T> {
  code: number;
  message: string;
  data: T | null;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => {
        // 假设响应类型为 Express 的 Response 类型，根据实际情况调整
        const httpResponse = context
          .switchToHttp()
          .getResponse<ExpressResponse>();
        const statusCode: number = httpResponse?.statusCode || 200; // 假设默认状态码为200
        return {
          code: statusCode,
          message: 'success',
          // 这里进行类型断言，确保 data 赋值时不会出现 unsafe assignment
          data: typeof data !== 'undefined' ? (data as T) : null,
        };
      }),
    );
  }
}
